//
//  LZManagePictureContentViewController.m
//  laziz_Merchant
//
//  Created by XMac on 17/3/9.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZManagePictureContentViewController.h"
#import "LZManagePictureCollectionViewCell.h"
#import "MJPhotoBrowser.h"
#import "extobjc.h"
#import "LZManagePicturePresenter.h"
#import "LZUserModel.h"
#import "LZPictureRejectCollectionReusableView.h"

@interface LZManagePictureContentViewController ()<UICollectionViewDelegateFlowLayout>

@property (strong, nonatomic) MJPhotoBrowser *brower;

@property (strong, nonatomic) NSMutableArray<NSDictionary *> *pictureDictionarys;


/**
 点击选择 ，将要删除的图片id数组
 */
@property (strong, nonatomic) NSMutableArray<NSString *> *selectedPictures;


/**
 collectionview使用的偏移宽度
 */
@property (nonatomic , assign) NSInteger offsetWidth;


@property (copy, nonatomic) void(^operationSelected)(PICTURE_OPERATION_TYPE type,NSString *photoId,LZManagePictureCollectionViewCell *cell);

@end

@implementation LZManagePictureContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configData];
    
    [self registerCell];
    
    [self configUI];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma
#pragma mark private method

-(void (^)(PICTURE_OPERATION_TYPE, NSString *, LZManagePictureCollectionViewCell *))operationSelected{
    if (!_operationSelected) {
        @weakify(self)
        _operationSelected = ^(PICTURE_OPERATION_TYPE type,NSString *photoId,LZManagePictureCollectionViewCell *cell){
            @strongify(self)
            
            if (self.isSingleSelected) {
                //先取消全部的 再打编辑 并设置cell的选择状态
                self.isEdit = NO;
                self.isEdit = YES;
                
                cell.isSelect = YES;
                
                [self.selectedPictures addObject:[NSString stringWithFormat:@"%@&&%@",cell.imageUrl,cell.bigImageUrl]];
            }else{
                //当前正在处理中
                __block BOOL isPossess = NO;
                //如果当前photo已经添加到了selectedPictures ，那么取消选中的时候需要从selectedPictures里面删除，所以需要对应的index下标。
                __block NSUInteger index = -1;
                
                [self.selectedPictures enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    isPossess = [obj isEqualToString:photoId];
                    if (isPossess) {
                        index = idx;
                        *stop = YES;
                    }
                }];
                
                switch (type) {
                    case PICTURE_OPERATION_ADD:
                        if (!isPossess) {
                            [self.selectedPictures addObject:photoId];
                        }
                        break;
                    case PICTURE_OPERATION_DELETE:
                        if (isPossess && index != -1) {
                            [self.selectedPictures removeObjectAtIndex:index];
                        }
                        break;
                }
            }
        };
    }
    
    return _operationSelected;
}


-(void)configData{
    
    _pictureDictionarys = @[].mutableCopy;
    
    _selectedPictures = @[].mutableCopy;
    
    [self requestPictureData];
}

-(void)configUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _brower = [[MJPhotoBrowser alloc] init];
    
    if (self.isCurrentVCNotChildVC) {
        
        self.navigationItem.title = LZLocalizedString(@"message_system", nil);
    }
}


-(void)registerCell{
    [self.collectionView registerNib:[UINib nibWithNibName:@"LZManagePictureCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"LZManagePictureCollectionViewCell"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BlankReusableView"];
    
    if (self.isCurrentVCNotChildVC) {
        [self.collectionView registerClass:[LZPictureRejectCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LZPictureRejectCollectionReusableView"];
    }
}


/**
 因为要计算cell的宽度，如果除以4会变成小数，会出现1像素的间隔，所以适当的进行偏移
 
 @return .
 */
-(NSInteger)getOffsetWidth{
    if (self.offsetWidth == 0) {
        NSInteger totalWidth = SCREEN_WIDTH - 50;
        NSInteger tmpTotalWidth = totalWidth;
        while (tmpTotalWidth%4 != 0) {
            tmpTotalWidth--;
        }
        self.offsetWidth = totalWidth - tmpTotalWidth;
    }
    return self.offsetWidth;
}


-(void)requestPictureData{
    LZManagePicturePresenter *presenter = [LZManagePicturePresenter new];
    
    void(^process)(id data)=^(id data){
        self.pictureDictionarys = [data mutableCopy];
        
        NSMutableArray *photos = [NSMutableArray array];
        if (self.pictureDictionarys.count > 0) {
            self.deleteReason = self.pictureDictionarys[0][@"deleteReason"];
            [self.collectionView reloadData];
        }
        
        [self.pictureDictionarys enumerateObjectsUsingBlock:^(NSDictionary *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MJPhoto *photo = [[MJPhoto alloc] init];
            photo.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",APIBaseImageUrl,obj[@"maxPhoto"]]];
            [photos addObject:photo];
        }];
        
        self.brower.photos = photos;
        
        [self.collectionView reloadData];
    };
    
    if (self.isCurrentVCNotChildVC) {
        [presenter getPictureRejectListWithDelBatch:self.delBatch Success:^(id data) {
            process(data);
        } Failure:^(NSString *fail) {
            DLog(@"%@",fail);
        }];
    }else{
        [presenter getPictureListWithSellId:[LZUserModel Instance].sellerId andPhotoType:[NSString stringWithFormat:@"%ld",self.index] Success:^(id data) {
            process(data);
        } Failure:^(NSString *fail) {
            DLog(@"%@",fail);
        }];
    }
}

#pragma
#pragma mark public method
-(void)refreshPictureData{
    [self requestPictureData];
}



-(void)setIsEdit:(BOOL)isEdit{
    
    _isEdit = isEdit;
    
    if (!self.isEdit) {
        //clean operation 取消edit状态的时候 把选择数组清空
        [self.selectedPictures removeAllObjects];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LZManagePictureCollectionViewCellEditNotification object:@(self.isEdit) userInfo:@{@"OPERATION_BLOCK":self.operationSelected}];
}


-(void)deleteOperation:(void(^)())deleteSuccess{
    if (self.selectedPictures.count > 0) {
        LZManagePicturePresenter *picturePresenter = [LZManagePicturePresenter new];
        
        [picturePresenter deletePictureWithSellId:[LZUserModel Instance].sellerId andPhotoIds:self.selectedPictures andToken:[LZUserModel Instance].userToken Success:^(id data) {
            [self refreshPictureData];
            
            
            if (deleteSuccess) {
                deleteSuccess();
            }
            
        } Failure:^(NSString *fail) {
            DLog(@"%@",fail);
        }];
    }
}

-(NSArray<NSString *> *)fetchSelectImageUrls{
    
    return self.selectedPictures;
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.pictureDictionarys.count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger offset = [self getOffsetWidth];
    
    CGFloat categoryWidth = (SCREEN_WIDTH - 50 - offset)/4;
    
    return CGSizeMake(categoryWidth, categoryWidth);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(10, 10, 0, 10);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LZManagePictureCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LZManagePictureCollectionViewCell" forIndexPath:indexPath];
    
    NSDictionary *dic = self.pictureDictionarys[indexPath.row];
    
    NSString *photoId = dic[@"id"];
    
    __block BOOL isPossess = NO;
    [self.selectedPictures enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        isPossess = [obj isEqualToString:photoId];
        if (isPossess) {
            *stop = YES;
        }
    }];
    
    cell.isEditing = self.isEdit;
    
    cell.isSelect = isPossess;
    
    cell.imageUrl = [NSString stringWithFormat:@"%@%@",APIBaseImageUrl,dic[@"photoUrl"]];
    
    cell.bigImageUrl = [NSString stringWithFormat:@"%@%@",APIBaseImageUrl,dic[@"maxPhoto"]];
    
    cell.photoId = photoId;
    
    cell.index = indexPath.row;
    
    @weakify(self)
    [cell setPictureTapBlock:^(NSInteger index, UIImageView *contentImageView, NSString *imageUrl) {
        @strongify(self)
        
        MJPhoto *photo = self.brower.photos[index];
        
        photo.srcImageView = contentImageView; //设置来源哪一个UIImageView
        
        self.brower.currentPhotoIndex = index;
        
        [self.brower show];
    }];
    
    [cell setOperationSelectedBlock:self.operationSelected];
    
    return cell;
}



-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (self.isCurrentVCNotChildVC) {
        return [LZPictureRejectCollectionReusableView getCurrentSizeWithReason:self.deleteReason];
    } else{
        return CGSizeZero;
    }
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (self.isCurrentVCNotChildVC) {
            LZPictureRejectCollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LZPictureRejectCollectionReusableView" forIndexPath:indexPath];
            [reusableView loadReasonText:self.deleteReason];
            return reusableView;
        }else{
            UICollectionReusableView *blank = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"BlankReusableView" forIndexPath:indexPath];
            return blank;
        }
    }
    
    return nil;
}


@end
